// pages/pay/pay.js
import httpsUtils from '../../utils/https.js';
import calcUtils from '../../utils/calcUtil.js';
import myUtils from '../../utils/util.js';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    color: '#FD910E',
    payType: 'wxPay',
    items: [
      { name: 'wxPay', value: '微信支付', checked: 'true', img: '../../static/image/x_cart/wx2.png' },
    ],
    orderId: '',
    goodsNumber: 0,
    orderMoney: 0.00,
    freightMoney: 0.00,
    payMoney: 0.00,
    balanceMoney: 0.00,

    isFocus: false,
    walletsPasswordFlag: false,
    setIsFocus: false,
    setwalletsPasswordFlag: false,
    money:1.00,
    isTab:1,  //1表示首页求购，2表示内部页求购
    btStatus: false, //支付按钮禁用
  },

  /**
   * 选择支付方式
   */
  radioChange: function (e) {
    var that = this;
    var payType = e.detail.value;
    if (payType == 'balPay') {
      if (calcUtils.sub(that.data.balanceMoney, that.data.payMoney) < 0) {
        wx.showModal({
          title: '提示',
          content: '余额不足',
          showCancel: false,
          success: function (res) {
            payType = 'wxPay';
            that.setData({
              payType: payType,
            })
          }
        })
      }
    }
    that.setData({
      payType: payType,
    })
  },
  /**
   * 获取账户余额
   */
  findBalance: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/user/buyDeatils1',
      data: '',
    }, function (json) {
      if (json.data && json.success) {
        var balanceMoney = 0.00;
        balanceMoney = json.data.balanceMoney;

        var payType = that.data.payType;
        if (calcUtils.sub(balanceMoney, that.data.payMoney) > 0) {
          payType = 'balPay';
        }

        that.setData({
          balanceMoney: balanceMoney.toFixed(2),
          payType: payType
        })
      }
    })
  },
  /**
   *初始化支付数据 
   */
  initOrder: function () {
    var that = this;
    var payOrders = wx.getStorageSync("payOrders");
    var goodsNumber = 0;
    var orderMoney = 0.00;
    var freightMoney = 0.00;
    var payMoney = 0.00;
    var ids = [];

    for (let order of payOrders) {
      goodsNumber = calcUtils.add(goodsNumber, order.goodsNumber);
      orderMoney = calcUtils.add(orderMoney, order.orderMoney);
      freightMoney = calcUtils.add(freightMoney, order.freightMoney);
      payMoney = calcUtils.add(payMoney, order.payMoney);
      ids.push(order.orderId);
    }

    that.setData({
      orderId: myUtils.concatStr(ids, ","),
      goodsNumber: goodsNumber,
      orderMoney: orderMoney.toFixed(2),
      freightMoney: freightMoney.toFixed(2),
      payMoney: payMoney.toFixed(2),
    })

  },
  /**
   * 去支付
   */
  toPay: function () {
    var that = this;
    var payType = that.data.payType;
    if (payType == 'balPay') {
      //余额支付
      var user = wx.getStorageSync("userInfo");
      if (myUtils.isBlank(user.payPwd)) {
        wx.showModal({
          title: '提示',
          content: '请先设置支付密码',
          showCancel:false,
          success:function(){
            that.setData({
              setIsFocus: true,
              setwalletsPasswordFlag: true,
            })
          }
        })
      } else {
        that.setData({
          isFocus: true,
          walletsPasswordFlag: true
        })
      }
    } else {
      that.setData({
        btStatus: true
      })
      wx.login({
        success: function (res) {
          var code = res.code;
          //微信支付
          that.wxPay(code);
        }
      })
    }
  },
  /**
   * 微信支付
   */
  wxPay:function(code){
    var that = this;
    wx.showLoading({
      title: '支付中...',
    })
    var cashMoney = that.data.money;
    if(cashMoney<=0){
      wx.showModal({
        title: '充值提示',
        content:'请输入充值金额',
        showCancel:false
      })
      return;
    }
    var orderId = that.data.orderId;
    httpsUtils.getData({
      _url: app.globalData._url + '/pay/wxpay2?isXcx=1&recoedType=1&cashMoney=' + cashMoney + "&wxCode=" + code,
      data: '',
    }, function (json) {
      wx.hideLoading();
      if(json.success){
        var data = json.data;
        wx.requestPayment(
          {
            'timeStamp': data.timeStamp,
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': 'MD5',
            'paySign': data.paySign,
            'success': function (res) { 
              that.setData({
                btStatus: false
              }) 
              wx.showToast({
                title: '支付成功',
                success: function () {
                  setTimeout(function () {
                    if(that.data.isTab == 1){
                      wx.switchTab({
                        url: '../askToBuyIssue/askToBuyIssue',
                      })
                    }else{
                      wx.redirectTo({
                        url: '../askToBuyIssue2/askToBuyIssue2',
                      })
                    }
                  }, 1000)
                }
              })
            },
            'fail': function (res) {
              that.setData({
                btStatus: false
              }) 
              wx.showToast({
                title: '支付失败'
              })
             },
            'complete': function (res) { }
          })
      }
    })
  },
  /**
   * 余额确认支付
   */
  submitPay: function (e) {
    var that = this;
    wx.showLoading({
      title: '支付中...',
    })
    var orderId = that.data.orderId;
    httpsUtils.getData({
      _url: app.globalData._url + '/pay/balanceMoney?payPassword=' + e.detail.password + "&orderId=" + orderId,
      data: '',
    }, function (json) {
      if (json.success) {
        wx.showToast({
          title: '支付成功',
          success: function () {
            setTimeout(function () {
              wx.redirectTo({
                url: '../myOrder/myOrder?type=0',
              })
            }, 1000)
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '支付失败' + json.msg,
          showCancel: false
        })
      }
      wx.hideLoading();
    })

  },
  /**
   * 设置支付密码
   */
  setPayPassword: function (e) {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/user/setPasswordMd5?payPassword=' + e.detail.password,
      data: '',
    }, function (json) {
      if (json.success) {
        wx.setStorageSync('userInfo', json.data);
        wx.showModal({
          title: '提示',
          content: '设置成功',
          showCancel: false,
          success: function (res) {
            that.toPay();
          }
        })
      }
    })
  },
  getPayMoney:function(e){
    var that = this;
    var money = e.detail.value;
    that.setData({
      money: money,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isTab:options.isTab,
      money: parseInt(options.money).toFixed(2)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //初始化支付订单
    this.initOrder();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})